<?php

namespace app\api\controller;

use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\Goods as GoodsModel;
use app\api\model\Cart as CartModel;
use app\common\service\qrcode\Goods as GoodsPoster;
use think\Db;
use app\api\model\meizhuang\MeizhuangComment as MeizhuangCommentModel;
use app\api\model\meizhuang\Ask as AskModel;
/**
 * 商品控制器
 * Class Goods
 * @package app\api\controller
 */
class Goods extends Controller
{
    /**
     * 商品列表
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        // 整理请求的参数
        $param = array_merge($this->request->param(), [
            'status' => 10
        ]);
        // 获取列表数据
        $model = new GoodsModel;
        $list = $model->getList($param, $this->getUser(false));
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 获取商品详情
     * @param $goods_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail($goods_id, $refereeId = null)
    {

        // 用户信息
        $user = $this->getUser(false);



        // // 记录推荐人关系
        // if ($user && $refereeId > 0) {

        //     //是否已存在推荐关系
        //     if (!RefereeModel::isExistReferee($user['user_id'])) {
        //         RefereeModel::createRelation($user['user_id'], $refereeId);
        //     }
        // }


        // 商品详情
        $model = new GoodsModel;

        $goods = $model->getDetails($goods_id, $this->getUser(false));

        if ($goods === false) {
            return $this->renderError($model->getError() ?: '商品信息不存在');
        }
        // 多规格商品sku信息, todo: 已废弃 v1.1.25
        $specData = $goods['spec_type'] == 20 ? $model->getManySpecData($goods['spec_rel'], $goods['sku']) : null;
        //获取首页推荐数据  郭涛add
        $wxapp_id=input('post.wxapp_id');
        $tuijianData=$this->getHot($wxapp_id);
        //获取产品参数  郭涛 add
        $productData=$this->getGoodsSku(1,$goods_id);
        //获取评价数据  郭涛 add
        $pingjiaData=$this->getPingJiaList($goods_id);
        //获取问大家数据  郭涛 add
        $wendajiaData=$this->getAskList($goods_id);
        //获取公告数据  郭涛 add
        $notice=$this->getNoticeList($wxapp_id);
        //获取收藏状态
        $collect=Db::name('meizhuang_collect')->where(['goods_id'=>$goods_id,'user_id'=>$user['user_id']])->find();
        if($collect){
            $collectStatus=1;
        }else{
            $collectStatus=0;
        }
        return $this->renderSuccess([
            //商品详情
            'detail' => $goods,
            'user_id' => $user['user_id']?$user['user_id']:0,
            //购物车商品总数量
            'cart_total_num' => $user ? (new CartModel($user))->getGoodsNum() : 0,
            //多规格商品sku信息
            'specData' => $specData,
            //郭涛add 首页推荐数据
            'tuijianData'=>$tuijianData,
            //郭涛add 产品参数数据
            'productData'=>$productData,
            //郭涛add 商品评价列表
            'pingjiaData'=>$pingjiaData,
            //郭涛add 问大家列表
            'wendajiaData'=>$wendajiaData,
            //郭涛 add 公告列表
            'notice'=>$notice,
            //收藏状态
            'collectStatus'=>$collectStatus
        ]);
    }
    /*
     * 历史提问list页面
     */
    private function getAskList($goods_id){
        $askModel=new AskModel();
        $goodWhere['goods_id']=$goods_id;
        $goodWhere['type']=1;
        $count=$askModel->getCount($goodWhere);//商品提问总数
        //获取问题列表 和一条回答信息
        $where['goods_id']=$goodWhere['goods_id'];
        $where['type']=1;
        $questionList=$askModel->getList($where);
        if($questionList){
            //获取提问回答总数
            foreach ($questionList as $k=>$v){
                $wheres['upid']=$v['id'];
                $huidaCount=$askModel->getList($wheres);
                $questionList[$k]['huidaCount']=count($huidaCount);
            }
        }
        $return['count']=$count;
        $return['askList']=$questionList;
        return $return;
    }
    /*
    * 获取商品评价列表
    */
    private function getPingJiaList($goods_id){
        $where['goods_id']=$goods_id;
        $where['status']=1;
        $commentList=(new MeizhuangCommentModel())->getList($where);
        $return['commentList']=$commentList;
        return $return;
    }
    /*
   * 获取产品参数or产品规格
   */
    private function getGoodsSku($type,$goods_id){
        $specrel=Db::name('goods_spec_rel')->where(['goods_id'=>$goods_id])->select();
        if(empty($specrel)){
            return $this->renderError([],'未获取到规格参数');
        }
        $newInfo=[];
        foreach ($specrel as $k=>$v){
            //查询规格名称
            $secInfo=Db::name('spec')->where(['spec_id'=>$v['spec_id']])->field('spec_id,spec_name')->find();
            //查询规格值
            $spec_value=Db::name('spec_value')->where(['spec_id'=>$v['spec_id']])->field('spec_id,spec_value,spec_value_id')->select();
            if($type==1){
                if(count($spec_value)==1){
                    $newInfo[]=[
                        'name'=>$secInfo['spec_name'],
                        'value'=>$spec_value[0]['spec_value']
                    ];
                }
            }else{
                if(count($spec_value)>1){
                    $a=[];
                    foreach ($spec_value as $k1=>$v1){
                        $a[]=$v1['spec_value'];
                    }
                    $newInfo[]=[
                        'name'=>$secInfo['spec_name'],
                        'value'=>$a
                    ];
                }
            }
        }
        return $newInfo;
    }
    /*
     * 美妆详情-热门推荐
     */
    private function getHot($wxapp_id){
        //获取最新四条热门推荐数据
        $list=Db::name('goods')
            ->alias('g')
            ->join('yoshop_goods_sku s','g.goods_id = s.goods_id')
            ->where('g.is_hot','=',1)
            ->where('g.wxapp_id','=',$wxapp_id)
            ->field('g.goods_name,g.goods_id,s.goods_price')
            ->order('g.create_time desc')
            ->limit(4)
            ->select();
        $list=$list->toArray();
        if($list){
            foreach($list as $k=>$v){
                //获取图片地址,只获取一张图片的地址
                $imageId=Db::name('goods_image')->where(['goods_id'=>$v['goods_id']])->field('image_id')->find();
                $uploadInfo=Db::name('upload_file')->where(['file_id'=>$imageId['image_id']])->find();
                $list[$k]['imageUrl']=$uploadInfo['file_url'].'/'.$uploadInfo['file_name'];
            }
        }
        return $list;
    }

    /*
     * 获取首页公告列表
     */
    public function getNoticeList($wxapp_id){
        $return=Db::name('notice')->where(['wxapp_id'=>$wxapp_id])->paginate(10, false, [
            'query' => \request()->request()
        ]);
        return $return;
    }

    /**
     * 生成商品海报
     * @param $goods_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function poster($goods_id)
    {
        // 商品详情
        $detail = GoodsModel::detail($goods_id);
        $Qrcode = new GoodsPoster($detail, $this->getUser(false));
        return $this->renderSuccess([
            'qrcode' => $Qrcode->getImage(),
        ]);
    }

}
